package com.mucd.chat.service.socketService;

import cn.hutool.core.lang.Pair;
import com.alibaba.fastjson2.JSONObject;
import com.mucd.chat.service.FriendRequestService;
import com.mucd.chat.utils.SessionContainer;
import com.ruoyi.common.constant.CacheConstants;
import com.ruoyi.common.core.domain.FriendRequest;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.core.redis.RedisCache;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.websocket.Session;
import java.util.HashMap;
import java.util.List;

/**
 * 上线后的service
 */
@Service
@Slf4j
public class OnlineSocketService {


    @Resource
    private FriendRequestService friendRequestService;
    @Resource
    private RedisCache redisCache;

    /**
     * 好友请求列表
     * 查询好友请求数量,将数量使用session发送到客户端
     *
     * @param loginUser 登录人
     * @param session   登录人session
     */
    public void selectNotReadNum(LoginUser loginUser, Session session) {

        HashMap<String, Integer> resMap = new HashMap<>();

        List<FriendRequest> list = friendRequestService.selectByStatusRequestsByReceiverId(loginUser);

        resMap.put("friendNum", list.size());
        resMap.put("chatListNum", list.size());
        resMap.put("trendsNum", list.size());

        session.getAsyncRemote().sendText(JSONObject.toJSONString(R.ok(resMap)));
    }


    /**
     * 设置用户在线状态
     *
     * @param loginUser    登录人
     * @param session      登录session
     * @param onlineStatus true上线 false下线
     */
    public void settingOnlineStatus(LoginUser loginUser, Session session, boolean onlineStatus) {
        log.info("设置{}用户在线状态:", loginUser.getUser().getUserId());
        Long userId = loginUser.getUser().getUserId();
        if (onlineStatus) {
            log.info("{}用户上线", userId);
            redisCache.setCacheObject(CacheConstants.CHAT_ONLINE_ON_KEY + userId, session.isOpen());
            SessionContainer.put(CacheConstants.CHAT_ONLINE_ON_KEY + userId, session);
        } else {
            log.info("{}用户下线", userId);
            redisCache.deleteObject(CacheConstants.CHAT_ONLINE_ON_KEY + userId);
            SessionContainer.deleteByKey(CacheConstants.CHAT_ONLINE_ON_KEY + userId);

        }
    }

    /**
     * 获取好友的在线状态,如果在线返回Session true, 如果不在线返回 null false
     *
     * @param userId 好友id
     */
    public Pair<Boolean,Session> selectOnlineStatus(Long userId) {
        //从redis获取是否在线,如果在线从内存中获取session
        if (redisCache.hasKey(CacheConstants.CHAT_ONLINE_ON_KEY + userId)) {
            Session session = SessionContainer.get(CacheConstants.CHAT_ONLINE_ON_KEY + userId);
            if (session != null && session.isOpen()) {
                return Pair.of(true,session);
            }
        }

        return Pair.of(false,null);
    }
}
